package kr.co.handysoft.project.smartPolice;

import java.io.File;
import java.io.IOException;
import java.util.List;

import kr.co.handysoft.common.registry.SmartPoliceRegistry;
import kr.co.handysoft.common.server.ControlServer;
import kr.co.handysoft.project.smartPolice.composite.WatchingDatabaseThreadMonitorComposite;
import kr.co.handysoft.project.smartPolice.composite.WatchingFileThreadMonitorComposite;
import kr.co.handysoft.smartPolice.server.WatchingDatabaseThread;
import kr.co.handysoft.smartPolice.server.WatchingFileThread;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.wb.swt.SWTResourceManager;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

public class SmartPoliceDataSender {

	protected Shell shlSmartPoliceData;
	private CTabFolder tabFolder;
	private Composite composite_1;
	private CTabItem tbtmControlServer;
	private List<Element> dirList;
	private List<Element> zoneList;

	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			SmartPoliceDataSender window = new SmartPoliceDataSender();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		initInformationServer();
		createContents();
		senderInit();
		shlSmartPoliceData.open();
		shlSmartPoliceData.layout();
		while (!shlSmartPoliceData.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}

	private void initInformationServer() {
		SAXBuilder builder = new SAXBuilder();
		String configFullPath = System.getProperty("deamon.config");
		Document doc;
		try {
			doc = builder.build(new File(configFullPath));
			SmartPoliceRegistry.setDocument(doc);
			SmartPoliceRegistry.setupInformationServerFromClient();
			if (doc.getRootElement().getAttributeValue("mode").equals("database")){

				Element dbElement = (Element)XPath.selectSingleNode(doc, "//databaseServer");
				String connectionURL = dbElement.getChild("connection").getAttributeValue("url");
				String connectionID = dbElement.getChild("connection").getAttributeValue("id");
				String connectionPW = dbElement.getChild("connection").getAttributeValue("password");
				int connectionIDLE = Integer.parseInt(dbElement.getChild("connection").getAttributeValue("idleCnt"));
				int connectionMAX = Integer.parseInt(dbElement.getChild("connection").getAttributeValue("maxConnection"));
				
				SmartPoliceRegistry.setupDataSource(connectionURL, connectionID, connectionPW, connectionIDLE, connectionMAX);
			}
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		
		shlSmartPoliceData = new Shell();
		shlSmartPoliceData.addListener(SWT.Close, new Listener() {

	        public void handleEvent(Event event) {
				
		        if (dirList != null){
		        	
		        	for (Element dirElement : dirList){
						String folderName = dirElement.getAttributeValue("part");
						SmartPoliceRegistry.setRunState(folderName , false);
						Button btn = (Button)SmartPoliceRegistry.getInvokeButton(folderName);
						if (btn != null){
							Event ev = new Event(); 
							ev.type = SWT.Selection; 
							ev.widget =  btn; 
							btn.notifyListeners(SWT.Selection, ev);
						}
						
					}
		        	
		        }
		        
		        if (zoneList != null){
		        	
		        	for (Element zoneElement : zoneList){
						String folderName = zoneElement.getAttributeValue("id");
						SmartPoliceRegistry.setRunState(folderName , false);
						Button btn = (Button)SmartPoliceRegistry.getInvokeButton(folderName);
						if (btn != null){
							Event ev = new Event(); 
							ev.type = SWT.Selection; 
							ev.widget =  btn; 
							btn.notifyListeners(SWT.Selection, ev);
						}
						
					}
		        	
		        }
		        
		        SmartPoliceRegistry.clientRunStat = false;
		        ControlServer ctrlServer = SmartPoliceRegistry.getClientControlServer();
		        if (ctrlServer != null) ctrlServer.close();

		        
	        	
	        	MessageBox box = new MessageBox(shlSmartPoliceData, SWT.OK | SWT.CANCEL | SWT.APPLICATION_MODAL);

	        	box.setMessage("Exit the application?");

	            event.doit = box.open() == SWT.OK;
	        	//if (event.doit) SmartPoliceRegistry.closeClientConnection();
		        
	            
	        }

	    });
		
		shlSmartPoliceData.setImage(SWTResourceManager.getImage(SmartPoliceDataSender.class, "/kr/co/handysoft/project/smartPolice/image/tiny_logo.png"));
		shlSmartPoliceData.setBackground(SWTResourceManager.getColor(SWT.COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT));
		shlSmartPoliceData.setSize(1150, 642);
		shlSmartPoliceData.setText("Smart Police Data Sender V1.0.0.0");
		shlSmartPoliceData.setLayout(new FormLayout());
		
		composite_1 = new Composite(shlSmartPoliceData, SWT.NONE);
		composite_1.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		RowLayout rl_composite_1 = new RowLayout(SWT.HORIZONTAL);
		rl_composite_1.wrap = false;
		rl_composite_1.marginLeft = 10;
		rl_composite_1.marginTop = 10;
		composite_1.setLayout(rl_composite_1);
		FormData fd_composite_1 = new FormData();
		fd_composite_1.left = new FormAttachment(0, 2);
		fd_composite_1.right = new FormAttachment(100, -2);
		fd_composite_1.height = 45;
		fd_composite_1.bottom = new FormAttachment(100, -2);
		composite_1.setLayoutData(fd_composite_1);
		
		tabFolder = new CTabFolder(shlSmartPoliceData, SWT.BORDER);
		tabFolder.setSimple(false);
		tabFolder.setTabHeight(23);
		FormData fd_tabFolder = new FormData();
		fd_tabFolder.top = new FormAttachment(0, 2);
		fd_tabFolder.bottom = new FormAttachment(composite_1, -2);

		fd_tabFolder.left = new FormAttachment(0, 2);
		fd_tabFolder.right = new FormAttachment(100, -2);
		tabFolder.setLayoutData(fd_tabFolder);
		tabFolder.setSelectionBackground(Display.getCurrent().getSystemColor(SWT.COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT));
		
		tbtmControlServer = new CTabItem(tabFolder, SWT.NONE);
		tbtmControlServer.setImage(SWTResourceManager.getImage(SmartPoliceDataSender.class, "/com/famfamfam/slik/icons/connect.png"));
		tbtmControlServer.setText("Control Server    ");
		
		tabFolder.setSelection(tbtmControlServer);
				
	}

	@SuppressWarnings("unchecked")
	private void senderInit() {
		SAXBuilder builder = new SAXBuilder();
		try {
			
			String configFullPath = System.getProperty("deamon.config");
			Document doc = builder.build(new File(configFullPath));
			SmartPoliceRegistry.setDocument(doc);
			
			if (doc.getRootElement().getAttributeValue("mode").equals("file")){
				initFileProcess(doc);
			}else{
				initDatabaseProcess(doc);
			}
			
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		composite_1.layout();
		tabFolder.setSelection(1);
		

	}

	private void initDatabaseProcess(Document doc) throws JDOMException {
		zoneList = XPath.selectNodes(doc, "//zones/zone" );			
		for (Element zoneElement : zoneList){
			
			final String zoneName = zoneElement.getAttributeValue("id");
			
			CTabItem tbtmNewItem = new CTabItem(tabFolder, SWT.NONE);
			tbtmNewItem.setImage(SWTResourceManager.getImage(SmartPoliceDataSender.class, "/com/famfamfam/slik/icons/server_go.png"));
			tbtmNewItem.setText(zoneName + "   ");
			
			WatchingDatabaseThread watchingThread = new WatchingDatabaseThread(zoneElement);
			tabFolder.setData(zoneName, watchingThread);
		
			WatchingDatabaseThreadMonitorComposite watchingDatabaseThreadMonitorComposite = new WatchingDatabaseThreadMonitorComposite(tabFolder, SWT.NONE);
			watchingDatabaseThreadMonitorComposite.setItem(zoneElement.getChildren("zone"));
			tbtmNewItem.setControl(watchingDatabaseThreadMonitorComposite);

			initButtonArea(zoneName, tbtmNewItem);

			SmartPoliceRegistry.setUpdateTarget(zoneName, watchingDatabaseThreadMonitorComposite);
			watchingThread.start();
		}
	}

	private void initFileProcess(Document doc) throws JDOMException {
		
		dirList = XPath.selectNodes(doc, "//directorys/directory" );	
		
		for (Element dirElement : dirList){
			
			final String folderName = dirElement.getAttributeValue("part");
			CTabItem tbtmNewItem = new CTabItem(tabFolder, SWT.NONE);
			tbtmNewItem.setImage(SWTResourceManager.getImage(SmartPoliceDataSender.class, "/com/famfamfam/slik/icons/server_go.png"));
			tbtmNewItem.setText(folderName + "   ");
			
			//start client data processing thread
			WatchingFileThread watchingThread = new WatchingFileThread(dirElement);
			tabFolder.setData(folderName, watchingThread);

			initButtonArea(folderName, tbtmNewItem);
			
			WatchingFileThreadMonitorComposite watchingThreadMonitorComposite = new WatchingFileThreadMonitorComposite(tabFolder, SWT.NONE);
			tbtmNewItem.setControl(watchingThreadMonitorComposite);
			SmartPoliceRegistry.setUpdateTarget(folderName, watchingThreadMonitorComposite);
			watchingThread.start();
		}
		
		SmartPoliceRegistry.getClientControlServer(doc).start();
	}
	

	private void initButtonArea(final String dispKeyName, CTabItem tbtmNewItem) {
		Button btnNewButton = new Button(composite_1, SWT.TOGGLE);
		btnNewButton.setData("item", tbtmNewItem);
		btnNewButton.setSelection(false);
		btnNewButton.setImage(SWTResourceManager.getImage(SmartPoliceDataSender.class, "/com/famfamfam/slik/icons/cross.png"));
		btnNewButton.setText(dispKeyName + " OFF");
		SmartPoliceRegistry.setRunState(dispKeyName , false);
		btnNewButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Button btn = (Button)e.getSource();
				SmartPoliceRegistry.setRunState(dispKeyName , btn.getSelection(), btn);
				if (btn.getSelection()){							
					btn.setText(dispKeyName + " ON");
					btn.setImage(SWTResourceManager.getImage(SmartPoliceDataSender.class, "/com/famfamfam/slik/icons/accept.png"));
				}else{
					btn.setText(dispKeyName + " OFF");
					btn.setImage(SWTResourceManager.getImage(SmartPoliceDataSender.class, "/com/famfamfam/slik/icons/cross.png"));
				}
				CTabItem tabItem = (CTabItem)btn.getData("item");
				tabFolder.setSelection(tabItem);
			}
		});
	}

}